# -*- coding=utf8 -*-
import logging
import json
import math
from lxml import etree
import requests
import time
from items import PospalMemberItem
from items import YouzanMemberItem
from items import YouzanMemberTaskItem
from youzan import pipelines
from mysqlmgr import mysqlmgr
from pospal import member_spider as pospal
import threading
import re
import time

name = 'youzan_member'
user_name = '13810807631'
password = 'ilb1eVdlRBCGka379mXqsw=='  # 'rfc8569008'
kdt_id = '19394396'
csrf_token = ''
captcha_url = 'https://login.youzan.com/sso/index/captcha'

# 导入时间间隔 1小时， 60*60*3
import_interval_time = 60*60*3
# 30分钟
session_refresh_time = 60*30
#设置头信息
headers_base = {
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
    'Accept-Encoding': 'gzip, deflate, sdch',
    'Accept-Language': 'en-US,en;q=0.8,zh-CN;q=0.6,zh;q=0.4,zh-TW;q=0.2',
    'Connection': 'keep-alive',
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.130 Safari/537.36',
    'Referer': 'http://www.zhihu.com/',
}
session = requests.session()
is_login = False


# 公共方法
def post(url, data=None, verify=False):
    return session.post(url=url, headers=headers_base, data=data, verify=verify)


# 公共方法
def get(url, data=None, verify=False):
    return session.get(url=url, headers=headers_base, data=data, verify=verify)

# 登录
def login():
    # 下载验证码
    response = get(url=captcha_url, verify=True)
    with open('youzan_captcha.png', 'wb') as f:
        # 下载图片必须以二进制来传输
        f.write(response.content)
        f.close()

    captcha = input("input youzan captcha: ")
    formdata = {
        'mobile': user_name,
        'password': password,
        'captcha_code': captcha,
        'country_code': '+86',
        'auto_login': 'on',
        'service': 'kdt'
    }
    url = 'https://uic.youzan.com/sso/index/login.json?service=kdt'
    # 使用seesion登录，这样的好处是可以在接下来的访问中可以保留登录信息
    response = post(url=url, data=formdata, verify=True)
    print(response.content)
    json_data = response.json()
    # 判断successed=true, 则继续执行，否则发送错误邮件给 xlpc_bj@163.com
    if json_data['code'] != 0:
        logging.error('after_login failed')
        return False
    else:
        global is_login
        is_login = True
        global csrf_token
        csrf_token = get_csrf_token()
        logging.info('csrf_token='+csrf_token)
        print('csrf_token=', csrf_token)
        return True


def get_csrf_token():
    # 直接到指定店铺
    selected_shop_url = 'https://www.youzan.com/v2/account/team/change.html?kdt_id=' + kdt_id +'&redirect='
    get(url=selected_shop_url)

    customer_url = 'https://www.youzan.com/scrm/customer/customer/index'
    response=get(url=customer_url)
    html = etree.HTML(response.content)
    script = html.xpath('/html/head/script[2]/text()')[0]  # /html/head/script[4].extract()
    # print(script)
    p2 = r'"csrf_token":.+?}'
    pattern2 = re.compile(p2)
    value = pattern2.findall(script)
    value = value[0]
    value = value[: len(value) -1] #去掉多余的}
    value = value.split(":")[1]
    value = value.replace('"', '') #替换"
    return value

# 导入用户数据，循环执行
def sync_members(loop=True):
    hour = time.strftime('%H', time.localtime(time.time()))
    if int(hour) in range(8, 24):
    # if int(hour) in range(0, 25):
        #https://www.youzan.com/scrm/customer/customer/getlist.json?p=7&csrf_token=xxx
        formdata = {
            'csrf_token': csrf_token,
        }
        # json
        response = post(url='https://www.youzan.com/scrm/customer/customer/getlist.json', data=formdata)
        '''
         {"code":0,"msg":"","data":{"total":140,"page":7,"pageSize":20,"list":[{}]}}
         '''
        json_data = response.json()
        if json_data['code'] != 0:
            logging.error('parse_customer_summary failed')
            return
        # 记录总数
        total_record = int(json_data['data']['total'])
        # 每页50
        page_size = 20
        # 计算总页数
        page_total = math.ceil(total_record / page_size)  # 向上取整
        # range(1, 5), 1,2,3,4
        for page_index in range(1, page_total + 1):
            post_load_member_by_page(page_index)

        # TODO 自动同步
        #deal_task()

        if loop is True:
            # 定时循环调用
            timer = threading.Timer(import_interval_time, sync_members, [True])
            timer.start()

# 提交会员页面
def post_load_member_by_page(page_index=1):
    formdata = {
        'p': str(page_index),
        'csrf_token': csrf_token,
    }
    response = post(url='https://www.youzan.com/scrm/customer/customer/getlist.json', data=formdata)
    json_data = response.json()
    # 判断successed=true, 则继续执行，否则发送错误邮件给 xlpc_bj@163.com
    if json_data['code'] != 0:
        logging.error('parse customer_summary failed')
        return
    list = json_data['data']['list']
    cur_datetime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
    for member in list:
        item = YouzanMemberItem()
        item['member_number'] = member['yzUid']
        item['real_name'] = member['name']
        item['mobile'] = member['mobile']
        item['member_point'] = member['points']
        item['is_enabled'] = '1'
        item['is_dealed'] = '0'
        item['create_time'] = cur_datetime
        item['modify_time'] = cur_datetime
        pipelines.process_item(item)

def deal_task():
    add_member_tasks, change_point_tasks = get_deal_task()
    deal_add_member_task(add_member_tasks)
    deal_change_point_task(change_point_tasks)


def deal_add_member_task(youzan_member_task_items):
    # 调用有赞接口，创建会员,PospalMemberItem
    for item in youzan_member_task_items:
        pospal.add_my_member(item)


def deal_change_point_task(youzan_member_task_items):
    # 调用有赞接口，增加积分,PospalMemberItem
    for item in youzan_member_task_items:
        pospal.change_my_point(item)


def get_deal_task():
    '''
    :return:  [YouzanMemberItem],[YouzanMemberItem]
    '''
    add_member_tasks = []
    change_point_tasks = []
    with mysqlmgr.mysql() as cursor:
        select_sql = 'select id, member_number, real_name, mobile, old_point, new_point, change_point,task_type, create_time,modify_time' \
                     ' from youzan_member_task where is_dealed=0'
        cursor.execute(select_sql)
        results = cursor.fetchall()
        for row in results:
            # 1:add_member,2:add_point
            if row['task_type'] == 1 :
                item = YouzanMemberTaskItem()
                item['id'] = row['id']
                item['member_number'] = row['member_number']
                item['real_name'] = row['real_name']
                item['mobile'] = row['mobile']
                item['new_point'] = row['new_point']
                item['old_point'] = row['old_point']
                item['change_point'] = row['change_point']
                item['create_time'] = row['create_time']
                item['modify_time'] = row['modify_time']
                add_member_tasks.append(item)
            elif row['task_type'] == 2 :
                item = YouzanMemberTaskItem()
                item['member_number'] = row['member_number']
                item['real_name'] = row['real_name']
                item['mobile'] = row['mobile']
                item['new_point'] = row['new_point']
                item['old_point'] = row['old_point']
                item['change_point'] = row['change_point']
                item['create_time'] = row['create_time']
                item['modify_time'] = row['modify_time']
                change_point_tasks.append(item)
        return add_member_tasks, change_point_tasks

# 保持session
def keep_session(loop=True):
    logging.info("keep session ... ...")
    global csrf_token
    csrf_token = get_csrf_token()
    logging.info('csrf_token=' + csrf_token)
    logging.info("keep session successfully")
    #
    if loop is True:
        timer = threading.Timer(session_refresh_time, keep_session, [True])
        timer.start()

def add_my_member(pospal_member_task_item):
    '''
    :param item: PospalMemberTaskItem
    '''
    # api
    formdata = {
        'is_member': '0',
        'is_validate': '1',
        'mobile': pospal_member_task_item['mobile'],
        'name': pospal_member_task_item['real_name'],
        csrf_token: csrf_token
    }
    response = post(url='https://www.youzan.com/scrm/customer/customer/createwithmobile.json', data=formdata)
    json_data = response.json()
    if json_data['code'] != 0: #{'code': 403, 'msg': 'Invalid token', 'data': ''}
        logging.error('add_my_member failed')
        logging.error(pospal_member_task_item)
        return

    logging.info('=========add youzan member successfully=========')
    logging.info(pospal_member_task_item)

    item = YouzanMemberItem()
    item['member_number'] = json_data['data']['yzUid']
    # item['member_number'] = pospal_member_task_item['mobile'] # FIXME
    item['mobile'] =  pospal_member_task_item['mobile']
    item['real_name'] =  pospal_member_task_item['real_name']
    item['member_point'] =  pospal_member_task_item['new_point']
    item['create_time'] =  pospal_member_task_item['create_time']
    item['modify_time'] =  pospal_member_task_item['modify_time']

    # 增加积分
    formdata = {
        'id': str(item['member_number']),
        'amount': str(pospal_member_task_item['change_point']),
        csrf_token: csrf_token
    }
    response = post(url='https://www.youzan.com/scrm/points/points/modify.json', data=formdata)
    json_data = response.json()
    if json_data['code'] != 0:
        logging.error('change point failed')
        logging.error(pospal_member_task_item)
        return

    # 数据库
    with mysqlmgr.mysql() as cursor:
        insert_history_sql = 'insert into youzan_member_history(member_number, real_name, mobile, member_point, is_enabled, is_dealed, create_time, modify_time)values(%s, %s, %s, %s, %s, %s, %s, %s)'
        params = (
            item['member_number'], item['real_name'], item['mobile'], item['member_point'], 1, 0,
            item['create_time'], item['modify_time'])
        cursor.execute(insert_history_sql, params)

        #is_deal=1
        udpate_task_sql = 'update pospal_member_task set is_dealed=1 where id=%s'
        params = pospal_member_task_item['id']
        cursor.execute(udpate_task_sql, params)


def change_my_point(pospal_member_task_item):
    '''
    :param item: PospalMemberTaskItem
    '''
    item = pipelines.get_from_history_by_mobile(pospal_member_task_item['mobile'])
    if item is None:
        return

    # 增加积分
    formdata = {
        'id': str(item['member_number']),
        'amount': str(pospal_member_task_item['change_point']),
        csrf_token: csrf_token
    }
    response = post(url='https://www.youzan.com/scrm/points/points/modify.json', data=formdata)
    json_data = response.json()
    if json_data['code'] != 0:
        logging.error('change point failed')
        return
    logging.info('=========change youzan point sucessfully=========')
    logging.info(pospal_member_task_item)

    # 数据库
    member_point = int(item['member_point']) + int(pospal_member_task_item['change_point'])
    with mysqlmgr.mysql() as cursor:
        insert_history_sql = 'insert into youzan_member_history(member_number, real_name, mobile, member_point, is_enabled, is_dealed, create_time, modify_time)values(%s, %s, %s, %s, %s, %s, %s, %s)'
        params = (
            item['member_number'], item['real_name'], item['mobile'], member_point, 1, 0,
            item['create_time'], item['modify_time'])
        cursor.execute(insert_history_sql, params)
        # is_deal=1
        udpate_task_sql = 'update pospal_member_task set is_dealed=1 where id=%s'
        params = pospal_member_task_item['id']
        cursor.execute(udpate_task_sql, params)


def exec_one():
    login_result = login()
    if login_result is False:
        print("error login failed")
        return exec_one()

    # 1.导入用户数据
    sync_members(loop=False)


if __name__=='__main__':
    exec_one()